<?php
namespace app\atxunda\controller;
use think\Controller;
use think\Db;
use think\Cache;
use think\Cookie;
use think\Request;
use PHPExcel\PHPExcel;
use app\index\model\Nav;
use app\index\model\Type;
use app\index\model\Course;
use app\index\model\Specific;
use app\atxunda\model\KnowUser;
use app\index\model\KnowUserVip;
use app\index\service\VipService;
use app\atxunda\model\AdminTraining;
use app\index\model\KnowUserTraining;
use app\index\model\KnowUserQuestion;


class User extends Common
{
	public function index(Request $request){
		$page = $request->param('page');
		$page = isset($page) ? $page : 1;
		$user_data = KnowUser::userAlls($request->param(),$this->admin);
		return $this->fetch('',[
			'page' => $page,
			'user_data' => $user_data,
			'param' => $request->param(),
			'admin_id' => $this->admin['admin_id'],
		]);
	}


	public function nav_price(Request $request){
		$param = $request->param();
		$data = KnowUser::field('know_phone,know_email')->where('know_user_id',$param['id'])->find();
		if(input('post.')){
			if($param['status'] == 0){
				KnowUserVip::where('user_id',$param['id'])->update([
					'valid' => 0,
					'updated_time' => date('Y-m-d H:i:s'),
				]);
			}else{
				if ($param['status'] == 1){
					KnowUserVip::insert([
						'user_id' => $param['id'],
						'valid' => 1,
						'action' => 1,
						'money' => 0,
						'updated_time' => date('Y-m-d H:i:s'),
						'created_time' => date('Y-m-d H:i:s'),
						'expired_time' => date('Y-m-d H:i:s',strtotime("+".($param['year'] ?: 10)." year")),

					]);
				} else if ($param['status'] == 2){
					KnowUserVip::setUserVip($param);
				}
			}
			$this->success('设置成功',url('index',['phone'=>$phone,'end_time'=>$end_time,'start_time'=>$start_time]),'',1);
		}else{
			$vips = VipService::disposeUserVip($param['id']);
			$status = 2;
			if ($vips){
				if ( $vips[1]) $status = 1;
			}
			$navData = Nav::getAllData();
			foreach($navData as &$v){
				$packIds = Db::table('nav_package')->where('nav_id',$v['nav_id'])->column('pack_id,price');
				$v['inputs'] = $vips[2][$v['nav_id']] ? 'input_edit' : 'input_new';
				$v['package'] = Db::table('package')->where('id','in',array_keys($packIds))->select();
				$v['moneys'] = $packIds;
				$v['userPack'] = Db::table('know_user_vip')->where('user_id',$param['id'])->where('nav_id',$v['nav_id'])->where('action',2)->value('pack_id');
				$v['type'] = Db::table('type')->where('nav_id',$v['nav_id'])->column('type_id,type_name');
			}
			return $this->fetch('vip',[
				'param' => $param,
				'data' => $data,
				'vips' => $vips,
				'status' => $status,
				'navData' => $navData,
			]);
		}
	}



	public function detail(){
		$request = Request::instance();
		$id = $request->param('id');
		$data = KnowUser::where('know_user_id',$id)
				->field('know_user_id,know_phone,know_email,know_nickname,register_time,register_ip,login_time,login_ip,salt,action,token')
				->find();
		return $this->fetch('',[
			'data' => $data,
		]);
	}

	public function changeremark(Request $request){
		$param = $request->param();
		KnowUser::where('know_user_id',$param['id'])->update(['know_remark'=>trim($param['remarks'])]);
	}

	public function locking(){
		$request = Request::instance();
		$param = $request->param();
		$userLock = KnowUser::where("know_user_id",$param['id'])->value('locking');
		if($userLock == 1){
			KnowUser::where("know_user_id",$param['id'])->update(['locking'=>0]);
			Db::table('know_user_lock')->insert([
				'user_id' => $param['id'],
				'is_locking' => 0,
				'start_time' => time(),
				'end_time' => time(),
				'created_admin_id' => $this->admin['admin_id'],
				'updated_admin_id' => $this->admin['admin_id'],
			]);
		}else{
			KnowUser::where("know_user_id",$param['id'])->update(['locking'=>1]);
			Db::table('know_user_lock')->where("user_id",$param['id'])->where('is_locking',0)->update([
				'is_locking' => 1,
				'end_time' => time(),
				'updated_admin_id' => $this->admin['admin_id'],
			]);
			$userData = KnowUser::where("know_user_id",$param['id'])->find();
			KnowUser::disposeExpireTime($userData);
		}
		$this->success('设置成功',url('index',['phone'=>$param['phone'],'end_time'=>$param['end_time'],'start_time'=>$param['start_time'],'page'=>$param['page']]),'',1);
	}


	public function document(){
		ini_set("memory_limit", "1024M");
		$user_id = input('post.user_id/a');
		$where = 1;
		if(is_array($user_id)){
			$user_id = implode(',',$user_id);
			$where .= " and know_user_id in ($user_id)";
		}
		$start_time = input('post.start_time');
		$end_time = input('post.end_time');
		if(!empty($start_time)){
			$start_time = strtotime($start_time);
			$where .= " and UNIX_TIMESTAMP(register_time)>=$start_time";
		}
		if(!empty($end_time)){
			$end_time = strtotime($end_time);
			$where .= " and UNIX_TIMESTAMP(register_time)<=$end_time";
		}
		$goods_list = KnowUser::field('know_user_id,know_nickname,know_phone,register_time,register_ip,login_time,login_ip,login_num')
					->where($where)
					->order('register_time desc')
					->select();
		if (empty($goods_list)) die(alert('暂无数据'));
		$data = array();
		foreach ($goods_list as $k=>$goods_info){
			$data[$k]['nickname'] = $goods_info['know_nickname'];
			$data[$k]['phone'] = $goods_info['know_phone'];
			$data[$k]['type'] = returnUserDispose($goods_info['know_user_id']);
			$data[$k]['register_time'] = $goods_info['register_time'];
			$data[$k]['register_ip'] = $goods_info['register_ip'];
			$data[$k]['login_time'] = $goods_info['login_time'];
			$data[$k]['login_ip'] = $goods_info['login_ip'];
			$data[$k]['login_num'] = $goods_info['login_num'];
		}
		$headArr = ['昵称','联系方式','会员身份','注册时间','注册ip','注册来源','最后登录时间','最后登录ip','登录次数'];
		$filename="user";
		$this->getExcel($filename,$headArr,$data);
	}

	public function getExcel($fileName,$headArr,$data){
		$fileName .= "_" . date("Y_m_d_H_i_s", Request::instance()->time());
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties();
		$key = ord("A"); // 设置表头
		foreach ($headArr as $v) {
			$colum = chr($key);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
			$key += 1;
		}
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(50);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
		$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();
		foreach ($data as $key => $rows) { // 行写入
			$span = ord("A");
			foreach ($rows as $keyName => $value) { // 列写入
				$objActSheet->setCellValue(chr($span) . $column, $value);
				$span++;
			}
			$column++;
		}
		$fileName = iconv("utf-8", "gb2312", $fileName); // 重命名表
		$objPHPExcel->setActiveSheetIndex(0); // 设置活动单指数到第一个表,所以Excel打开这是第一个表
		header('Pragma:public');
		header('Content-Type:application/x-msexecl;name="$fileName.xls"');
		header("Content-Disposition:inline;filename=\"$fileName.xls\"");
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');// 文件通过浏览器下载
		exit();
	}


	public function question(Request $request){
		$admin = $this->admin;
		$admin_data = Db::table('admin')->field('nav_id,role_id')->where('admin_id',$admin['admin_id'])->find();
		$param = $request->param();
		$query = $param;
		if(!empty($admin['nav_id'])) $param['nav_id'] = $where['nav_id'] = $admin['nav_id'];
		$data = KnowUserQuestion::getAllData($param, $query);
		$nav_data = Nav::getAllData($where);
		return $this->fetch('',[
			'data' => $data,
			'param' => $param,
			'nav_data' => $nav_data,
		]);
	}


	public function answer(Request $request){
		$param = $request->param();
		$data = KnowUserQuestion::getOneData($param);
		if(input('post.')){
			$admin = $this->admin;
			if($param['content'] || $param['answer']){
				KnowUserQuestion::insert([
					'content' => $param['content'],
					'pid' => $param['id'],
					'time' => date('Y-m-d H:i:s'),
					'user_id' => 0,
					'nav_id' => $data['nav_id'],
					'type_id' => $data['type_id'],
					's_id' => $data['s_id'],
					'course_id' => $data['course_id'],
					'course_id' => $param['course_id'],
					'admin_id' => $admin['admin_id'],
					'updated_admin_id' => $admin['admin_id'],
					'updated_time' => date('Y-m-d H:i:s'),
					'answer' => 1,
				]);
				KnowUserQuestion::where('id',$param['id'])->update([
					'answer' => 1,
					'updated_admin_id' => $admin['admin_id'],
					'updated_time' => date('Y-m-d H:i:s')
				]);
			}
			$this->success('点评成功',url('question').'?page='.$page,'',1);
		}else{
			$answer = KnowUserQuestion::where('pid',$param['id'])
							->order('time asc')
							->select();
			return $this->fetch('',[
				'data' => $data,
				'answer' => $answer
			]);
		}
	}

	
	public function changeQuestion(Request $request){
		$id = $request->param('id');
		$content = $request->param('content');
		KnowUserQuestion::where(['id'=>$id])->update([
			'content'=>$content,
			'updated_admin_id'=>$this->admin['admin_id'],
			'updated_time' => time(),
		]);
	}

	public function training(Request $request){
		$param = $request->param();
		$admin = $this->admin;
		$data = KnowUserTraining::getAllData($param);
		if($admin['role_id'] != 1 && !empty($admin['nav_id']))
			$where['nav_id'] = $param['nav_id'] = $admin['nav_id'];
		$type_data = Type::getNavData($param['nav_id']);
		$s_data = Specific::getWhereTypeData($param);
		$course_data = Course::getTrainData($param);
		$nav_data = Nav::getAllData($where);
		return $this->fetch('',[
			'data' => $data,
			's_data' => $s_data,
			'nav_data' => $nav_data,
			'type_data' => $type_data,
			'course_data' => $course_data,
		]);
	}


	public function dianping(Request $request){
		$param = $request->param();
		$data = KnowUserTraining::getOneData($param);
		if(input('post.')){
			$admin = $this->admin;
			$data = array(
				'admin_id' => $admin['admin_id'],
				'content' => $param['content'],
				'kuc_id' => $param['id'],
				'course_id' => $data['course_id'],
				'time' => date('Y-m-d H:i:s'),
			);
			$t_data = AdminTraining::getUserData($param['id']);
			KnowUserTraining::where('id',$param['id'])->update([
				'grade'=>$param['grade'],
				'status'=>1
			]);
			if($t_data){
				AdminTraining::where('id',$t_data['id'])->update($data);
			}else{
				AdminTraining::insert($data);
			}
			$this->success("操作成功",url('student'),'',1,'window.close();window.opener.location.reload();');
		}else{
			return $this->fetch('',[
				'data' => $data,
			]);
		}
	}

}
